﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace ChinaDynastyTours.Helpers
{
    //IUserService就是WCF的ServiceContract，是客户端自动生成的代理类
    //调用代码一:WcfClient.UseService((IUserService userService) => (userService.GetUser(userId)));
    //调用代码而：WcfClient.UseService<IUserService , User>(s => s.GetUser(userId));
    //WcfClient实现代码：
    public class WcfClient
    {
        public static TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> func)
        {
            var chanFactory = new ChannelFactory<TChannel>("*");
            TChannel channel = chanFactory.CreateChannel();
            TReturn result = func(channel);
            try
            {
                ((IClientChannel)channel).Close();
            }
            catch
            {
                ((IClientChannel)channel).Abort();
            }
            return result;
        }
        /// <summary>
        /// 支持无返回值的WCF服务调用,调用方法：WcfClient.UseService<IFeedService>(s => s.BeginCreate(feed, null, null));
        /// </summary>
        /// <typeparam name="TChannel"></typeparam>
        /// <param name="action"></param>
        public static void UseService<TChannel>(Action<TChannel> action)
        {
            var chanFactory = new ChannelFactory<TChannel>("*");
            TChannel channel = chanFactory.CreateChannel();
            ((IClientChannel)channel).Open();
            action(channel);
            try
            {
                ((IClientChannel)channel).Close();
            }
            catch
            {
                ((IClientChannel)channel).Abort();
            }
        }
    }
}